package com.ruoyi.web.controller.glzz;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.web.controller.dao.GpsDao;
import com.ruoyi.web.controller.dao.TShipDeviceSubject;
import com.ruoyi.web.controller.dao.ValueImportExcel;
import com.ruoyi.web.controller.dao.ValueImportForExcel;
import com.ruoyi.web.service.glzz.ITGlzzMenuService;
import com.ruoyi.web.service.glzz.TShipDeviceSubjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;

/**
 * glzz菜单Controller
 *
 * @author sci
 * @date 2024-05-13
 */
@SuppressWarnings({"DefaultAnnotationParam", "PointlessBooleanExpression"})
@Api(value = "glzz菜单", tags = {"工具接口"})
@RestController
@RequestMapping("/system/utilsApi")
@Slf4j
public class TGlzzImportUtilController extends BaseController {
    @Autowired
    private ITGlzzMenuService tGlzzMenuService;




        @ApiOperation("导入数据传入到时序数据库,时序数据库")
    @PostMapping("excel/importValueExcelToDatabase")
    public AjaxResult excelImport(@RequestParam("file") MultipartFile file) throws IOException {

        String token = "XBq3Ri4i1gioB8owwOjK0NnG8M1kAc0SJNoxtxtcHAKSSdKfJilZwMT3YChVslAAR7_L4erJD4F6sWXVaziY5g==";
        String bucket = "dev";
        String org = "glzz";


        ExcelUtil<ValueImportExcel> util = new ExcelUtil<>(ValueImportExcel.class);
//      格式、数据校验
        List<ValueImportExcel> valueList = util.importExcel(file.getInputStream());
        while(valueList.size()<1000000){
            valueList.addAll(valueList);
        }
//      业务校验、存储
        // 初始化时间戳为2024年1月1日
        int threadCount = 100;
        List<InfluxDBClient> clients = new ArrayList<>(threadCount);
        for (int i = 0; i < threadCount; i++) {
            clients.add(null);
        }

        ForkJoinPool forkJoinPool = new ForkJoinPool(threadCount);
        forkJoinPool.execute(() ->{
            Stream.iterate(0, i -> i + 1).limit(valueList.size())
                    .parallel()
                    .forEach(i -> {
                        int idx = i % threadCount;
                        InfluxDBClient client = clients.get(idx);
                        if (client == null) {
                            synchronized (Integer.valueOf(idx)) {
                                client = clients.get(idx);
                                if (client == null) {
                                    client = InfluxDBClientFactory.create("http://localserver:8086", token.toCharArray());
                                    clients.set(idx, client);
                                }
                            }
                        }
                        WriteApiBlocking writeApi = client.getWriteApiBlocking();
                        ValueImportExcel valueImportExcel = valueList.get(i % valueList.size()); // 循环使用列表中的数据
                        Double value = valueImportExcel.getValue();
                        Instant now = Instant.now();

                        Point point = Point
                                .measurement("mem")
                                .addTag("host", "host1")
                                .addField("used_percent", value)
                                .time(now, WritePrecision.NS);

                        writeApi.writePoint(bucket, org, point);
                    });
        });

//        Point point = Point
//                .measurement("mem")
//                .addTag("host", "host1")
//                .addField("used_percent", 23.43234543)
//                .time(Instant.now(), WritePrecision.NS);
//
//        WriteApiBlocking writeApi = client.getWriteApiBlocking();
//        writeApi.writePoint(bucket, org, point);
        return AjaxResult.success();
    }
    @ApiOperation("导入文件读取里边的内容转成json返回")
    @PostMapping("importForGetJson")
    public AjaxResult importForGetJson(@RequestParam("file") MultipartFile file) throws IOException {
        List<String> paragraphs = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             XWPFDocument document = new XWPFDocument(inputStream)) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                paragraphs.add(paragraph.getText());
            }
            // 这里将段落列表作为JSON的一部分返回
            // 你可以根据需要构建更复杂的JSON结构
            return AjaxResult.success(paragraphs.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("读取文件失败"); // 或者返回具体的错误信息
        }
    }
}
